package com.android.lovely.api.encrypt

import android.util.Base64
import com.android.lovely.BuildConfig
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

val AES_KEY = "\u0000\u0000\u0000${
    BuildConfig.API_HOST.substringAfter("://").substring(3, 8)
}\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"


object AesEncryptHelper {

    fun encode(key: String = AES_KEY, content: String): String {
        return runCatching {
            val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
            val secretKeySpec = SecretKeySpec(key.toByteArray(), "AES")
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, IvParameterSpec(key.toByteArray()))
            return Base64.encodeToString(cipher.doFinal(content.toByteArray()), Base64.NO_WRAP)
        }.getOrDefault("")
    }

    /**
     * AES解密
     */
    fun decode(key: String = AES_KEY, content: String): String {
        return runCatching {
            val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
            val secretKeySpec = SecretKeySpec(key.toByteArray(), "AES")
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, IvParameterSpec(key.toByteArray()))
            val result = cipher.doFinal(Base64.decode(content, Base64.NO_WRAP))
            return result.decodeToString()
        }.getOrDefault("")
    }
}